<script setup lang="ts">
  import Header from './Header.vue'
  import Table from './Table.vue'
  import Pagination from '@/components/Pagination/index.vue'
  import { computed, ref } from 'vue'

  defineOptions({
    name: 'CustomFieldReturnFactory',
  })

  const tableInstance = ref<InstanceType<typeof Table> | null>(null)
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)
  const getListKeyword = ref('')
  const listTotal = computed(() => {
    if (tableInstance.value) {
      return tableInstance.value.total
    }
    return 0
  })
  const selectedFieldIds = ref<Array<string>>([])

  const handleUpdateList = (keyword: string) => {
    getListKeyword.value = keyword
    getList()
  }

  const getList = () => {
    if (tableInstance.value && paginationInstance.value) {
      tableInstance.value.getList({
        name: getListKeyword.value,
        limit: paginationInstance.value.size || 50,
        page: paginationInstance.value.current || 1,
      })
    }
  }

  const handleSelectField = (fieldIds: Array<string>) => {
    selectedFieldIds.value = fieldIds
  }

  defineExpose({
    getList,
  })
</script>

<template>
  <div class="custom-field-return-factory">
    <Header :selected-field-ids="selectedFieldIds" @update="handleUpdateList"></Header>
    <div class="table">
      <Table ref="tableInstance" @select-field="handleSelectField"></Table>
    </div>
    <div class="pagination">
      <Pagination
        :list_total="listTotal"
        @current-change="getList"
        @size-change="getList"
        ref="paginationInstance"
      ></Pagination>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .custom-field-return-factory {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    // padding: 12px;
    display: flex;
    flex-direction: column;
    row-gap: 5px;

    .table {
      max-height: calc(100% - 66px);
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
